/**
 * 内存栅栏
 * 
 * 当获取操作能看到释放栅栏操作后的结果，那么这个栅栏就与获取操作同步
 */
#include <iostream>
#include <atomic>
#include <thread>
#include <assert.h>

std::atomic<bool> x, y;
std::atomic<int> z;

void write_x_then_y() {
    x.store(true, std::memory_order_relaxed);
    // 增加栅栏
    std::atomic_thread_fence(std::memory_order_release);
    y.store(true, std::memory_order_relaxed);
}

void read_y_then_x() {
    while (!y.load(std::memory_order_relaxed));
    // 释放栅栏与获取栅栏同步
    std::atomic_thread_fence(std::memory_order_acquire);
    // x必定为true
    if (x.load(std::memory_order_relaxed)) {
        ++z;
    }
}

int main(int argc, char const *argv[])
{
    x = false;
    y = false;
    z = 0;
    std::thread a(write_x_then_y);
    std::thread b(read_y_then_x);

    a.join();
    b.join();

    std::cout << "z is " << z << std::endl;
    
    return 0;
}
